package com.pingan.agentbank.aaos.util;

import com.pingan.agentbank.aaos.exception.AAOSException;
import com.pingan.agentbank.aaos.pojo.BusiData;
import com.pingan.agentbank.aaos.pojo.Config;
import com.pingan.agentbank.aaos.pojo.RequestInfo;
import com.pingan.agentbank.aaos.pojo.SysHeader;
import com.pingan.vframe.Controller;
import com.pingan.vframe.SystemConfig;
import com.pingan.vframe.logging.Log;
import com.pingan.vframe.logging.LogFactory;
import com.pingan.vframe.util.GBKProperties;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class ConfigUtil {


    private static final Log log = LogFactory.getLog();

    public static Config loadConfig(String orgCode){

        GBKProperties props = SystemConfig.getInstance().getProperties("com."+orgCode+".");
        GBKProperties defaultProps = SystemConfig.getInstance().getProperties("com.default.");

        Config config = new Config();
        config.setBank(orgCode);


        if (props.getProperty("sourDir")==null){
            config.setSourDir("/nas/cardOutPlat/"+orgCode+"/sourDir");
        } else {
            config.setSourDir(props.getProperty("sourDir"));
        }

        if (props.getProperty("backDir")==null){
            config.setBackDir("/nas/cardOutPlat/"+orgCode+"/backDir");
        } else {
            config.setBackDir(props.getProperty("backDir"));
        }

        if (props.getProperty("descDir")==null){
            config.setDescDir("/nas/cardOutPlat/"+orgCode+"/descDir");
        } else {
            config.setDescDir(props.getProperty("descDir"));
        }

        if (props.getProperty("fieldsDir")==null){
            config.setFieldsDir("/nas/cardOutPlat/"+orgCode+"/fieldsDir");
        } else {
            config.setFieldsDir(props.getProperty("fieldsDir"));
        }

        if (props.getProperty("fileNameFilter")==null){
            config.setFileNameFilter(orgCode+"-APPROVAL-[0-9]{8}-[0-9]{1,5}\\.ok");
        } else {
            config.setFileNameFilter(props.getProperty("fileNameFilter"));
        }

        if (props.getProperty("sourCode")==null){
            config.setSourCode(defaultProps.getProperty("sourCode"));
        } else {
            config.setSourCode(props.getProperty("sourCode"));
        }

        if (props.getProperty("descCode")==null){
            config.setDescCode(defaultProps.getProperty("descCode"));
        } else {
            config.setDescCode(props.getProperty("descCode"));
        }

        //获取行分隔符
        String lineSeparator = props.getProperty("lineSeparator");
        if ("window".equals(lineSeparator)){
            lineSeparator = "\r\n";
        } else {
            lineSeparator = "\n";
        }
        config.setLineSeparator(lineSeparator);


        if (props.getProperty("indbInterval")==null){
            config.setIndbInterval(Integer.valueOf(defaultProps.getProperty("indbInterval")));
        } else {
            config.setIndbInterval(Integer.valueOf(props.getProperty("indbInterval")));
        }

        if (props.getProperty("taskInterval")==null){
            config.setTaskInterval(Integer.valueOf(defaultProps.getProperty("taskInterval")));
        } else {
            config.setTaskInterval(Integer.valueOf(props.getProperty("taskInterval")));
        }

        if (props.getProperty("backUpOverDue")==null){
            config.setBackUpOverDue(Integer.valueOf(defaultProps.getProperty("backUpOverDue")));
        } else {
            config.setBackUpOverDue(Integer.valueOf(props.getProperty("backUpOverDue")));
        }

        if (props.getProperty("backUpCleanInterval")==null){
            config.setBackUpCleanInterval(Integer.valueOf(defaultProps.getProperty("backUpCleanInterval")));
        } else {
            config.setBackUpCleanInterval(Integer.valueOf(props.getProperty("backUpCleanInterval")));
        }

        if (props.getProperty("dbOverDue")==null){
            config.setDbOverDue(Integer.valueOf(defaultProps.getProperty("dbOverDue")));
        } else {
            config.setDbOverDue(Integer.valueOf(props.getProperty("dbOverDue")));
        }

        if (props.getProperty("dbCleanInterval")==null){
            config.setDbCleanInterval(Integer.valueOf(defaultProps.getProperty("dbCleanInterval")));
        } else {
            config.setDbCleanInterval(Integer.valueOf(props.getProperty("dbCleanInterval")));
        }

        if (props.getProperty("AaisRemoteCall")==null){
            config.setAaisRemoteCall(defaultProps.getProperty("AaisRemoteCall"));
        } else {
            config.setAaisRemoteCall(props.getProperty("AaisRemoteCall"));
        }

        if (props.getProperty("AcrsRemoteCall")==null){
            config.setAcrsRemoteCall(defaultProps.getProperty("AcrsRemoteCall"));
        } else {
            config.setAcrsRemoteCall(props.getProperty("AcrsRemoteCall"));
        }

        if (props.getProperty("endLineEmpty")==null){
            config.setEndLineEmpty(defaultProps.getProperty("endLineEmpty"));
        } else {
            config.setEndLineEmpty(props.getProperty("endLineEmpty"));
        }


        //指定映射配置文件
        config.setTaskConfig(orgCode+".xml");
        //设置数据源
        config.setDbName("dbsource/"+orgCode.toLowerCase(Locale.ENGLISH)+"_mysql");
        //加载xml文件
        Document doc = loadXML(config);
        //加载审批必输字段
        config.setApproFileds(loadApproFileds(doc));
        //加载网申必输字段
        config.setAaisFileds(loadAaisFileds(doc));

        //加载网申调用字段
        config.setRequestInfo(loadAAISFileds(doc));

        //加载脚本
        loadScript(doc,config);
        return config;
    }

    /*
    * 加载每家银行的XML配置
    */
    private static Document loadXML(Config config){
        InputStream resourceAsStream = null;

        try {
            resourceAsStream = new FileInputStream(Controller.getInstance().getVFramePath() +
                    "/config/aaos/" + config.getTaskConfig());
        } catch (Exception e) {
            e.printStackTrace();
        }

        //获取任务配置
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = null;
        Document doc = null;

        try {
            builder = factory.newDocumentBuilder();
            doc = builder.parse(resourceAsStream);
        } catch (ParserConfigurationException e) {
            log.error(e.getMessage());
            throw new AAOSException(e.getMessage());
        } catch (SAXException e) {
            log.error(e.getMessage());
            throw new AAOSException(e.getMessage());
        } catch (IOException e) {
            log.error(e.getMessage());
            throw new AAOSException(e.getMessage());
        }
        return doc;
    }

    /*
     *获取银行对应脚本的String
     */
    private static void loadScript(Document doc,Config config){

        String toServiceDataScript = doc.getElementsByTagName("toServiceDataScript").item(0).getFirstChild().getNodeValue();
        String toResultStringScript = doc.getElementsByTagName("toResultStringScript").item(0).getFirstChild().getNodeValue();

        LineHandler lineHandler = ClassGenarateUtil.generateLineHandler(config.getBank(),toServiceDataScript,toResultStringScript);

        config.setLineHandler(lineHandler);
    }

    /*
    * 获取网申字段，从AAIS获取
    */
    private static RequestInfo loadAAISFileds(Document doc){


        SysHeader sysHeader = new SysHeader();
        if (doc.getElementsByTagName("timestamp").item(0).getFirstChild()!=null){
            sysHeader.setTimestamp(doc.getElementsByTagName("timestamp").item(0).getFirstChild().getNodeValue());
        }
        if (doc.getElementsByTagName("appId").item(0).getFirstChild()!=null){
            sysHeader.setAppId(doc.getElementsByTagName("appId").item(0).getFirstChild().getNodeValue());
        }
        if (doc.getElementsByTagName("transcode").item(0).getFirstChild()!=null){
            sysHeader.setTranscode(doc.getElementsByTagName("transcode").item(0).getFirstChild().getNodeValue());
        }
        if (doc.getElementsByTagName("orgCode").item(0).getFirstChild()!=null){
            sysHeader.setOrgCode(doc.getElementsByTagName("orgCode").item(0).getFirstChild().getNodeValue());
        }

        BusiData busiData = new BusiData();
        if (doc.getElementsByTagName("queryType").item(0).getFirstChild()!=null){
            busiData.setQueryType(doc.getElementsByTagName("queryType").item(0).getFirstChild().getNodeValue());
        }
        if (doc.getElementsByTagName("applyNum").item(0).getFirstChild()!=null){
            busiData.setApplyNum(doc.getElementsByTagName("applyNum").item(0).getFirstChild().getNodeValue());
        }

        if (doc.getElementsByTagName("queryPara").item(0).getFirstChild()!=null){
            String queryPara = doc.getElementsByTagName("queryPara").item(0).getFirstChild().getNodeValue();
            String[] strings = queryPara.split(",");
            List<String> list = new ArrayList<>();

            for (String s:strings){
                list.add(s);
            }
            busiData.setQueryPara(list);
        }

        RequestInfo requestInfo = new RequestInfo();
        requestInfo.setSysHeader(sysHeader);
        requestInfo.setBusiData(busiData);
        return requestInfo;
    }

    /*
    * 获取审批必输字段，用于校验
    */
    private static String[] loadApproFileds(Document doc){
        if (doc.getElementsByTagName("approFileds").item(0).getFirstChild()!=null){
            String string = doc.getElementsByTagName("approFileds").item(0).getFirstChild().getNodeValue();
            String[] strings = string.split(",");
            return strings;
        }
        return null;
    }


    /*
     * 获取网申必输字段，用于校验
     */
    private static String[] loadAaisFileds(Document doc){

        if (doc.getElementsByTagName("aaisFileds").item(0).getFirstChild()!=null){
            String string = doc.getElementsByTagName("aaisFileds").item(0).getFirstChild().getNodeValue();
            String[] strings = string.split(",");
            return strings;
        }
        return null;
    }
}
